package cn.zh.aop.aspect;

import cn.zh.aop.anno.TargetDataSource;
import cn.zh.aop.component.DataSourceManagement;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author zh
 */
@Component
@Slf4j
@Aspect
public class TargetDataSourceAspect {

    @Pointcut("@annotation(cn.zh.aop.anno.TargetDataSource)")
    public void pointcut() {
    }

    @Before("pointcut()")
    public void choiceDataSource(JoinPoint joinPoint){
        TargetDataSource annotation = null;
        Class<?> target = joinPoint.getTarget().getClass();
        // 类上是否存在注解
        boolean present = target.isAnnotationPresent(TargetDataSource.class);
        if (present){
            annotation = target.getAnnotation(TargetDataSource.class);
            log.info("类上标注了注解。v：{}",annotation.value());
        }else {
            Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
            // 方法上判断是否存在注解
            if (method.isAnnotationPresent(TargetDataSource.class)){
                annotation = method.getAnnotation(TargetDataSource.class);
                log.info("方法上标注了注解。v：{}",annotation.value());
            }
        }
        if (annotation != null){
            DataSourceManagement.flag.set(annotation.value().name());
        }
    }

}
